/**
 * 查询角色列表
 */
const { QueryPage, promiseMap } = require('../../../utils')
Parse.Cloud.define('getAdminUsers', async (req, res) => {
  const { pageSize, currentPage } = req.params
  const user = req.user
  if (!user) {
    return res.error('请先登录')
  }
  const permission = { sessionToken: user.getSessionToken() }
  try {
    // 拥有登录后台的角色
    const loginRole = await new Parse.Query(Parse.Role).equalTo('name', 'Login').first(permission)
    // 获取登录角色下的所有子角色
    const roles = await loginRole.getRoles().query().find(permission)
    // user query
    const querys = roles.map(item => item.getUsers().query())
    const queryPage = new QueryPage('User', pageSize, currentPage)
    queryPage.setQuery(Parse.Query.or(...querys))
    const result = await queryPage.fetch(['username', 'updatedAt', 'status'], '', permission)
    // 获取角色
    result.data = await promiseMap(result.data, (item) => {
      return new Promise((resolve, reject) => {
        const currentUser = new Parse.User()
        currentUser.id = item.id
        new Parse.Query(Parse.Role).containedIn('users', [currentUser]).find(permission).then((userRoles) => {
          item.roles = userRoles.map((userRole) => {
            return {
              id: userRole.id,
              name: userRole.get('name')
            }
          })
          resolve(item)
        }).catch((err) => {
          console.log(err)
          reject(err)
        })
      })
    })
    res.success(result)
  } catch (err) {
    console.log(err)
    res.error(err.message)
  }
})
